<template>
    <div class="header">
        <a href="#/">
            <img src="@/assets/vue.svg" class="logo">
            <span class="company">RBAC学员管理系统</span>
        </a>
        <el-dropdown @command="handleCommand" style="border: 0;" trigger="click">
            <span class="el-dropdown-link">
                {{ userStore.user?.name }}
                <el-icon class="el-icon--right"><arrow-down></arrow-down></el-icon>
            </span>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item command="a">修改密码</el-dropdown-item>
                    <el-dropdown-item command="b">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        <span class="date">{{ currentTime }}</span>

        <!-- 修改密码对话框 dialogFormVisible为true时对话框显示，否则隐藏 -->
        <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
            <el-form :model="userForm" ref="userFormRef" label-width="100px" label-position="right" :rules="rules">
                <el-form-item label="原始密码" prop="oldPass">
                    <el-input v-model="userForm.oldPass" type="password">
                    </el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="pass">
                    <el-input v-model="userForm.pass" type="password">
                    </el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="userForm.checkPass" type="password">
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="updatePwd(userFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue';
import { formateTime } from '@/utils/dateUtils';
import { onMounted, reactive, ref } from 'vue';
// 引入用户小仓库
import useUserStore from '@/store/modules/user';
let userStore = useUserStore()
// 引入路由
import { useRouter } from 'vue-router';
import {type FormRules, type FormInstance } from 'element-plus';
import { reqCheckPwd, reqUpdatePwd } from '@/api/user';
const $router = useRouter()
const handleCommand = (command: string | number | object) => {
    switch (command) {
        case 'a':
            // 修改密码
            dialogFormVisible.value = true
            break;
        case 'b':
            // 退出登录
            handleLogout()
            break;
        default:
            break;
    }
}
// // 退出登录
// const handleLogout = () => {
//     userStore.removeUser()
//     if (!userStore.user) {
//         $router.replace("/login")
//     }
// }

// 要显示的当前系统时间 
let currentTime = ref<string>('')
const getTime = () => {
    setInterval(() => {
        currentTime.value = formateTime(Date.now())
    }, 1000);
}
onMounted(() => {
    getTime()
})


// 退出登录方法
const handleLogout = () => {
    userStore.removeUser()
    $router.replace('/login')
};
// 修改密码弹出是否提示
const dialogFormVisible = ref(false);
// 修改密码表达数据收集对象
const userForm = reactive({
    oldPass:'',
    pass:'',
    checkPass:'',
});
// 表达ref对象
const userFormRef = ref()
// 校验原密码自定义规则
const validateOldPass = (_rule: any, value: any,callback: any) => {
    reqCheckPwd({userId:(userStore.user?._id as string),password:value}).then(response=>{
        if(response.status == 0){
            callback()
        }else{
            callback(new Error(response.msg))
        }
    })
};
// 校验确认密码自定义规则
const validateCheckPass = (_rule: any, value: any, callback: any) => {
    if (value !== userForm.pass){
        callback(new Error("两次密码输入不一致"))
    }else{
        callback();
    }
}
// 表达校验规则
const rules = reactive<FormRules>({
    oldPass:[{required:true,validator:validateOldPass,trigger:'blur'}],
    pass:[{required:true,message:'请输入新密码',trigger:'blur'}],
    checkPass:[{required:true,validator:validateCheckPass,trigger:'blur'}]
});
// 确定按钮点击回调函数
const updatePwd = (formEl: FormInstance | undefined) => {
    if(!formEl) return
    formEl.validate((valid) => {
        if(valid) {
            // 调用接口修改密码
            reqUpdatePwd({userId:(userStore.user?._id as string),password:userForm.pass}).then(response=>{
                // 如果修改成功
                if(response.status == 0){
                    // 退出登录
                    handleLogout()
                    // 关闭对话框
                    dialogFormVisible.value = false
                }
            })
        }else{
            console.log('error submit!');
        }
    })
}
</script>

<style scoped>
.logo {
    vertical-align: middle;
    padding: 0 10px 0 40px;
    width: 25px;
    height: 25px;
}

.company {
    position: absolute;
    color: white;
}

/* 下拉菜单 */
.el-dropdown {
    float: right;
    margin-right: 40px;
    height: 50px;
    line-height: 50px;
}

.el-dropdown-link {
    cursor: pointer;
    color: #fff;
}

.date {
    float: right;
    color: #fff;
    margin-right: 50px;
}
</style>